package com.springboot.lotterysystem.controller;

import com.springboot.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.springboot.lotterysystem.common.exception.ControllerException;
import com.springboot.lotterysystem.common.pojo.CommonResult;
import com.springboot.lotterysystem.common.utils.JacksonUtil;
import com.springboot.lotterysystem.controller.param.UserRegisterParam;
import com.springboot.lotterysystem.controller.result.UserRegisterResult;
import com.springboot.lotterysystem.service.UserService;
import com.springboot.lotterysystem.service.dto.UserRegisterDTO;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-04-20
 * Time: 14:29
 */
@RestController
public class UserController {

    // 创建日志对象
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource(name = "userServiceImpl")
    private UserService userService;

    /**
     * 注册接口
     * @param param 注册参数
     * @return 返回统一数据格式
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    // 加上 @Validated注解 之后，表明对应的参数需要进行验证，而其验证规则就需要加到对应的类中
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody UserRegisterParam param) {
        // 打印日志信息
        logger.info("userRegister UserRegisterParam {}", JacksonUtil.writeValueAsString(param));
        // 调用service层的服务，并返回结果
        UserRegisterDTO userRegisterDTO = userService.register(param);
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }

    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO register) {
        UserRegisterResult result = new UserRegisterResult();
        if (register == null) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        result.setUserId(register.getUserId()); // 这里要用register内部的属性，首先得确保不是null
        return result;
    }
}
